import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

/* Layout */
import store from '@/store/'
import Layout from '@/layout'
// import { getToken } from '@/utils/auth'

export const routes = [
  {
    path: '/login',
    component: () => import('@/views/Login/index'),
    hidden: true
  },
  {
    path: '/',
    component: Layout,
    redirect: '/workbench'
  },
  {
    path: '/workbench',
    component: Layout,
    children: [{
      path: '',
      component: () => import('@/views/Workbench/index'),
      meta: { title: '工作台', icon: 'el-icon-data-board' },
      hidden: false
    }]
  },
  // 行车记录-添加月卡
  {
    path: '/add-card',
    component: () => import('@/views/Car/CarCard/addCard.vue')
  },
  // 企业管理-添加企业
  {
    path: '/add-ep',
    component: () => import('@/views/Park/Enterprise/add-ep.vue')
  },
  // 企业管理-查看企业详情信息
  {
    path: '/ep-detail',
    component: () => import('@/views/Park/Enterprise/ep-detail.vue')
  },
  {
    // 系统管理-员工管理-添加角色
    path: '/add-role',
    component: () => import('@/views/System/Role/add-role.vue')
  },
  {
    // 一体杆管理-告警记录-详情
    path: '/warning',
    component: () => import('@/views/Rod/RodWarn/warning.vue')
  }
]

export const asyncRoutes = [
  {
    path: '/park',
    component: Layout,
    permission: 'park',
    meta: { title: '园区管理', icon: 'el-icon-office-building' },
    children: [{
      path: 'building',
      permission: 'park:building',
      meta: { title: '楼宇管理' },
      component: () => import('@/views/Park/Building/index')
    },
    {
      path: 'enterprise',
      permission: 'park:enterprise',
      meta: { title: '企业管理' },
      component: () => import('@/views/Park/Enterprise/index')
    }]
  },
  {
    path: '/parking',
    component: Layout,
    permission: 'parking',
    meta: { title: '行车管理', icon: 'el-icon-guide' },
    children: [{
      path: 'area',
      permission: 'parking:area',
      component: () => import('@/views/Car/CarArea'),
      meta: { title: '区域管理' }
    }, {
      path: 'card',
      permission: 'parking:card',
      component: () => import('@/views/Car/CarCard'),
      meta: { title: '月卡管理' }
    }, {
      path: 'pay',
      permission: 'parking:payment',
      component: () => import('@/views/Car/CarPay'),
      meta: { title: '停车缴费管理' }
    },
    {
      path: 'rule',
      permission: 'parking:rule',
      component: () => import('@/views/Car/CarRule'),
      meta: { title: '计费规则管理' }
    }]
  },
  {
    path: '/pole',
    component: Layout,
    permission: 'pole',
    meta: { title: '一体杆管理', icon: 'el-icon-refrigerator' },
    children: [{
      path: 'info',
      permission: 'pole:info',
      component: () => import('@/views/Rod/RodManage'),
      meta: { title: '一体杆管理' }
    }, {
      path: 'waring',
      permission: 'pole:warning',
      component: () => import('@/views/Rod/RodWarn'),
      meta: { title: '告警记录' }
    }]
  },
  {
    path: '/sys',
    component: Layout,
    permission: 'sys',
    meta: { title: '系统管理', icon: 'el-icon-setting' },
    children: [{
      path: 'role',
      permission: 'sys:role',
      component: () => import('@/views/System/Role/index'),
      meta: { title: '角色管理' }
    }, {
      path: 'user',
      permission: 'sys:user',
      component: () => import('@/views/System/Employee/index'),
      meta: { title: '员工管理' }
    }]
  },
  {
    path: '/propety',
    component: Layout,
    permission: 'property',
    children: [{
      // 注意：这里路径字符串为空，代表一级菜单无二级菜单
      path: '',
      name: 'cost',
      permission: 'propertyFee',
      // 二级路由点，要挂载的组件
      component: () => import('@/views/Propety/index'),
      // 左侧路由上标题和图标（图标使用 element-ui 组件库里图标类名（因为左侧导航组件是基于 element-ui 组件库）
      meta: { title: '物业费管理', icon: 'el-icon-wallet' },
      hidden:false
    }]
  }
]

const createRouter = () => new Router({
  // mode: 'history', // require service support
  mode: 'history', //历史模式-路由模式
  scrollBehavior: () => ({ y: 0 }),
  routes: routes
})

const router = createRouter()

// 重置路由方法
export function resetRouter() {
  // 得到一个全新的router实例对象
  const newRouter = createRouter()
  // 使用新的路由记录覆盖掉老的路由记录
  router.matcher = newRouter.matcher
}

router.beforeEach(async(to, from, next) => {
  const whiteList = ['/login']
  const token = store.state.user.token
  if (token) {
    next()
    if (!store.state.user.profile.id) {
      const userRouter = []
      const res = await store.dispatch('user/getProfile')
      // console.log('验证权限',res)
      store.commit('user/setUserName', res.data.roleName)
      const resultList = []
      res.data.permissions.forEach(item => {
        // item.split(':') =>>> 'park:rule:list' =>>>> ['park','rule','list']
        resultList.push(item.split(':')[0])
      })
      // 数组去重
      const firstPerList = Array.from(new Set(resultList))
      // console.log('first', firstPerList)
      if (firstPerList[0] === '*') {
        userRouter.push(...routes)
        userRouter.push(...asyncRoutes) // 将筛选后的数组添加到路由数组里面
        // 用户切换时会闪404 bug
        const arrRouter = []
        arrRouter.push({
          path: '*',
          component: () => import('@/views/404'),
          hidden: true
        })
        arrRouter.push(...userRouter)
        store.commit('user/setUserRouter', arrRouter)
        arrRouter.forEach(objRouter => {
          router.addRoute(objRouter)
        })
      } else {
        let secondPerList = res.data.permissions.map(item => {
          const index = item.lastIndexOf(':')
          const targetStr = item.substring(0, index)
          return targetStr
        })
        secondPerList = Array.from(new Set(secondPerList))
        // 数组去重
        // console.log('筛选二级路由的组', secondPerList)
        // let newObj = {}
        const routerArr = asyncRoutes.filter(obj => {
          return firstPerList.includes(obj.permission)
        })

        const routesList = routerArr.map(obj => {
          const resultArr = obj.children.filter(item => {
            return secondPerList.includes(item.permission)
          })
          const newObj = { ...obj }
          newObj.children = resultArr
          return newObj
        })

        // console.log('筛选后的所有路由', routesList)
        const arrRouter = []
        userRouter.push(...routes)
        userRouter.push(...routesList) // 将筛选后的数组添加到路由数组里面
        arrRouter.push(...userRouter)
        arrRouter.push({
          path: '*',
          component: () => import('@/views/404'),
          hidden: true
        })
        store.commit('user/setUserRouter', arrRouter)
        arrRouter.forEach(objRouter => {
          router.addRoute(objRouter)
        })
        // console.log('筛选后的路由', router)
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
